package xin.nick.common.core.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xin.nick.common.core.constant.SystemConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QueryUtil {

    private static final String TOKEN_REGEX_STRING = "Bearer\\s(.+)";
    private static final Pattern TOKEN_PATTERN = Pattern.compile(TOKEN_REGEX_STRING);

    public static ServletRequestAttributes getRequestAttributes() {
        try {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes) attributes;
        } catch (Exception e) {
            return null;
        }
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes = getRequestAttributes();
        return Objects.requireNonNull(servletRequestAttributes).getRequest();
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletRequestAttributes = getRequestAttributes();
        return Objects.requireNonNull(servletRequestAttributes).getResponse();
    }

    public static <T> Page<T> getQueryPage() {
        HttpServletRequest request = getRequest();
        String sizeString = request.getParameter("size");
        String currentString = request.getParameter("current");
        long current = 1L;
        long size = 10L;

        try {
            size = Long.parseLong(sizeString);
            current = Long.parseLong(currentString);
        } catch (Exception ignored) {

        }

        return new Page<>(current, size);
    }

    /**
     * 从请求中获取token
     *
     * @param request HttpServletRequest
     * @return String
     */
    public static String getToken(HttpServletRequest request) {


        String token = request.getHeader(SystemConstants.TOKEN_KEY);

        String authorizationToken = request.getHeader(SystemConstants.HEADER_AUTHORIZATION);
        if (StringUtils.hasLength(authorizationToken)) {
            Matcher m = TOKEN_PATTERN.matcher(authorizationToken);
            if (m.find()) {
                token = m.group(1);
            }
        }

        if (!StringUtils.hasLength(token)) {
            token = request.getHeader(SystemConstants.TOKEN_KEY);
            if (!StringUtils.hasLength(token)) {
                token = request.getParameter(SystemConstants.TOKEN_KEY);
            }
        }

        return token;

    }
}
